package com.leaves.common.util;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

/**
 * @Author: LEAVES
 * @Version 1.0
 * @Date: 2022年08月01日  11时04分08秒
 * @Description: AES算法加密
 */
public class AesEncrypt {

    //--------------AES---------------
    /**
     * 密匙，必须16位
     */
    private static final String KEY = "suntoon@11270000";
    /**
     * 编码
     */
    private static final String ENCODING = "UTF-8";
    /**
     * 算法
     */
    private static final String ALGORITHM = "AES";
    /**
     * 默认的加密算法，ECB模式
     */
    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    /**
     * AES加密
     *
     * @param data
     * @return String
     */
    public static String AESEncrypt(String data) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(KEY.getBytes(), "AES"));
        byte[] b = cipher.doFinal(data.getBytes("utf-8"));
        //采用base64算法进行转码,避免出现中文乱码
        return Base64.encodeBase64String(b);
    }

    /**
     * AES解密
     *
     * @param data
     * @return String
     */
    public static String AESDecrypt(String data) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(KEY.getBytes(), "AES"));
        byte[] b = cipher.doFinal(Base64.decodeBase64(data));
        //采用base64算法进行转码,避免出现中文乱码
        return new String(b);
    }

    public static void main(String[] args) throws Exception {
        String mi = AesEncrypt.AESEncrypt("Lc@1234");
        System.out.println(mi);
        String ma = AesEncrypt.AESDecrypt(mi);
        System.out.println(ma);

    }
}
